package com.lebang.service.cences;

import com.lebang.domain.CencesOutlay;
import com.lebang.domain.DownloadMemberRecord;
import com.lebang.domain.MemberClidkRouseRecord;
import com.lebang.example.CencesOutlayExample;
import com.lebang.mapper.CencesOutlayMapper;
import com.lebang.mapper.LbbMemberMapper;
import com.lebang.mapper.MemberNewTradeMapper;
import com.lebang.model.MyConfig;
import com.lebang.model.Whether;
import com.lebang.model.cences.CencesMsg;
import com.lebang.model.cences.OutLayCount;
import com.lebang.model.cences.SdkMoney;
import com.lebang.model.enums.buss.DownStatus;
import com.lebang.model.enums.buss.RewardTypeUscan;
import com.lebang.service.BaseService;
import com.lebang.service.mongodb.CencesMsgMongodb;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import static com.lebang.model.enums.buss.TaskCategory.*;

/**
 * 统计
 *
 * @Author hwq
 * @Date 2020-02-10
 */
@Service@Slf4j
public class CencesOutlayService extends BaseService<CencesOutlay, Integer, CencesOutlayExample> {
    @Autowired
    private CencesOutlayMapper baseMapper;
    @Autowired
    private LbbMemberMapper lbbMemberMapper;

    @Autowired
    private MemberNewTradeMapper memberNewTradeMapper;
    @Autowired
    private CencesMsgMongodb cencesMsgMongodb;

    public void starDataInit(LocalDateTime end) {
        this.starDataInit(end,null);
    }
    public void starDataInit(LocalDateTime end, List<String> brand) {
        long starTime=System.currentTimeMillis();
        DateTimeFormatter df = DateTimeFormatter.ofPattern("yyyyMMdd");
        LocalDateTime star = end.minusDays(1);
        LocalDate starDate = star.toLocalDate();
        int time = Integer.parseInt(end.toLocalDate().minusDays(1).format(df));
        List<CencesOutlay> cencesMasters = new ArrayList<>();
        if(brand==null){
            brand=lbbMemberMapper.selectBrand();
        }

        List<OutLayCount> outLayCounts = memberNewTradeMapper.countGroupByCategory(star,end);
        outLayCounts.forEach(s->{s.setCategoryAppMember(s.getCategory()+":"+s.getAppStore()+":"+s.getIsNewMember());});
        Map<String,List<OutLayCount>> outLayMap = outLayCounts.stream().collect(Collectors.groupingBy(OutLayCount::getCategoryAppMember));

        StringBuffer category = new StringBuffer();

        //全部用户的
        brand.forEach(s -> {
            CencesOutlay newVo = new CencesOutlay(0, s, time, 1, 0, MyConfig.getEnv());
            CencesOutlay oldVo = new CencesOutlay(0, s, time, 0, 0,MyConfig.getEnv());
            CencesOutlay allVo = new CencesOutlay(0, s, time, 2, 0,MyConfig.getEnv());
            //新手任务
            category.replace(0,category.length(),NEW_HAND.name());
            oldVo.setNewhandMoney(countUserMoney(outLayMap,category, Whether.NO.getDbIndex(),s));
            newVo.setNewhandMoney(countUserMoney(outLayMap,category, Whether.YES.getDbIndex(),s));
            allVo.setNewhandMoney(oldVo.getNewhandMoney().add(newVo.getNewhandMoney()));
            //截图任务
            category.replace(0,category.length(),Common.name());
            oldVo.setRecordMoney(countUserMoney(outLayMap,category, Whether.NO.getDbIndex(),s));
            newVo.setRecordMoney(countUserMoney(outLayMap,category, Whether.YES.getDbIndex(),s));
            allVo.setRecordMoney(oldVo.getRecordMoney().add(newVo.getRecordMoney()));
            //CPL
            //闲玩
            category.replace(0,category.length(),XianWan.name());
            oldVo.setXianwanMoney(countUserMoney(outLayMap,category, Whether.NO.getDbIndex(),s));
            newVo.setXianwanMoney(countUserMoney(outLayMap,category, Whether.YES.getDbIndex(),s));
            allVo.setXianwanMoney(oldVo.getXianwanMoney().add(newVo.getXianwanMoney()));
            oldVo.setSdkMoney(oldVo.getSdkMoney().add(oldVo.getXianwanMoney()));
            newVo.setSdkMoney(newVo.getSdkMoney().add(newVo.getXianwanMoney()));
            allVo.setSdkMoney(allVo.getSdkMoney().add(allVo.getXianwanMoney()));
            //傲天
            category.replace(0,category.length(),AoTian.name());
            oldVo.setAotianMoney(countUserMoney(outLayMap,category, Whether.NO.getDbIndex(),s));
            newVo.setAotianMoney(countUserMoney(outLayMap,category, Whether.YES.getDbIndex(),s));
            allVo.setAotianMoney(oldVo.getAotianMoney().add(newVo.getAotianMoney()));
            oldVo.setSdkMoney(oldVo.getSdkMoney().add(oldVo.getAotianMoney()));
            newVo.setSdkMoney(newVo.getSdkMoney().add(newVo.getAotianMoney()));
            allVo.setSdkMoney(allVo.getSdkMoney().add(allVo.getAotianMoney()));
            //看视频
            //CSJ
            category.replace(0,category.length(),CHUANGSHANJIA.name());
            oldVo.setVideoMoney(countUserMoney(outLayMap,category, Whether.NO.getDbIndex(),s));
            newVo.setVideoMoney(countUserMoney(outLayMap,category, Whether.YES.getDbIndex(),s));
            allVo.setVideoMoney(oldVo.getVideoMoney().add(newVo.getVideoMoney()));
            //GDT
            category.replace(0,category.length(),GDT.name());
            oldVo.setVideoMoney(oldVo.getVideoMoney().add(countUserMoney(outLayMap,category, Whether.NO.getDbIndex(),s)));
            newVo.setVideoMoney(newVo.getVideoMoney().add(countUserMoney(outLayMap,category, Whether.YES.getDbIndex(),s)));
            allVo.setVideoMoney(oldVo.getVideoMoney().add(newVo.getVideoMoney()));

            //BD
            category.replace(0,category.length(),BAIDUSP.name());
            oldVo.setVideoMoney(oldVo.getVideoMoney().add(countUserMoney(outLayMap,category, Whether.NO.getDbIndex(),s)));
            newVo.setVideoMoney(newVo.getVideoMoney().add(countUserMoney(outLayMap,category, Whether.YES.getDbIndex(),s)));
            allVo.setVideoMoney(oldVo.getVideoMoney().add(newVo.getVideoMoney()));

            //淘金
            category.replace(0,category.length(),TAOJIN.name());
            oldVo.setTaojinMoney(countUserMoney(outLayMap,category, Whether.NO.getDbIndex(),s));
            newVo.setTaojinMoney(countUserMoney(outLayMap,category, Whether.YES.getDbIndex(),s));
            allVo.setTaojinMoney(oldVo.getTaojinMoney().add(newVo.getTaojinMoney()));
            oldVo.setSdkMoney(oldVo.getSdkMoney().add(oldVo.getTaojinMoney()));
            newVo.setSdkMoney(newVo.getSdkMoney().add(newVo.getTaojinMoney()));
            allVo.setSdkMoney(allVo.getSdkMoney().add(allVo.getTaojinMoney()));
            //聚享玩
            category.replace(0,category.length(),JUXIANGWAN.name());
            oldVo.setJuxiangwanMoney(countUserMoney(outLayMap,category, Whether.NO.getDbIndex(),s));
            newVo.setJuxiangwanMoney(countUserMoney(outLayMap,category, Whether.YES.getDbIndex(),s));
            allVo.setJuxiangwanMoney(oldVo.getJuxiangwanMoney().add(newVo.getJuxiangwanMoney()));
            oldVo.setSdkMoney(oldVo.getSdkMoney().add(oldVo.getJuxiangwanMoney()));
            newVo.setSdkMoney(newVo.getSdkMoney().add(newVo.getJuxiangwanMoney()));
            allVo.setSdkMoney(allVo.getSdkMoney().add(allVo.getJuxiangwanMoney()));
            //乐享多游
            category.replace(0,category.length(),LEXIANG.name());
            oldVo.setDuoyouMoney(countUserMoney(outLayMap,category, Whether.NO.getDbIndex(),s));
            newVo.setDuoyouMoney(countUserMoney(outLayMap,category, Whether.YES.getDbIndex(),s));
            allVo.setDuoyouMoney(oldVo.getDuoyouMoney().add(newVo.getDuoyouMoney()));
            oldVo.setSdkMoney(oldVo.getSdkMoney().add(oldVo.getDuoyouMoney()));
            newVo.setSdkMoney(newVo.getSdkMoney().add(newVo.getDuoyouMoney()));
            allVo.setSdkMoney(allVo.getSdkMoney().add(allVo.getDuoyouMoney()));

            category.replace(0,category.length(),YW_HZ.name());
            oldVo.setYwhzMoney(countUserMoney(outLayMap,category, Whether.NO.getDbIndex(),s));
            newVo.setYwhzMoney(countUserMoney(outLayMap,category, Whether.YES.getDbIndex(),s));
            allVo.setYwhzMoney(oldVo.getYwhzMoney().add(newVo.getYwhzMoney()));
            oldVo.setSdkMoney(oldVo.getSdkMoney().add(oldVo.getYwhzMoney()));
            newVo.setSdkMoney(newVo.getSdkMoney().add(newVo.getYwhzMoney()));
            allVo.setSdkMoney(allVo.getSdkMoney().add(allVo.getYwhzMoney()));
            //PC蛋蛋

            category.replace(0,category.length(),PCDANDAN.name());
            oldVo.setPceggMoney(countUserMoney(outLayMap,category, Whether.NO.getDbIndex(),s));
            newVo.setPceggMoney(countUserMoney(outLayMap,category, Whether.YES.getDbIndex(),s));
            allVo.setPceggMoney(oldVo.getPceggMoney().add(newVo.getPceggMoney()));
            oldVo.setSdkMoney(oldVo.getSdkMoney().add(oldVo.getPceggMoney()));
            newVo.setSdkMoney(newVo.getSdkMoney().add(newVo.getPceggMoney()));
            allVo.setSdkMoney(allVo.getSdkMoney().add(allVo.getPceggMoney()));

            category.replace(0,category.length(),CSJ_ZXR.name());
            oldVo.setEarnMoney(countUserMoney(outLayMap,category, Whether.NO.getDbIndex(),s));
            newVo.setEarnMoney(countUserMoney(outLayMap,category, Whether.YES.getDbIndex(),s));
            allVo.setEarnMoney(oldVo.getEarnMoney().add(newVo.getEarnMoney()));
//            //签到支出
            category.replace(0,category.length(),EARN_CLICK.name());
            oldVo.setEarnClcikMoney(countUserMoney(outLayMap,category, Whether.NO.getDbIndex(),s));
            newVo.setEarnClcikMoney(countUserMoney(outLayMap,category, Whether.YES.getDbIndex(),s));
            allVo.setEarnClcikMoney(oldVo.getEarnClcikMoney().add(newVo.getEarnClcikMoney()));
            //师徒支出
            category.replace(0,category.length(),MASTER.name());
            oldVo.setMasterMoney(countUserMoney(outLayMap,category, Whether.NO.getDbIndex(),s));
            newVo.setMasterMoney(countUserMoney(outLayMap,category, Whether.YES.getDbIndex(),s));
            allVo.setMasterMoney(oldVo.getMasterMoney().add(newVo.getMasterMoney()));
            //转盘抽奖
            category.replace(0,category.length(),ZPCJ.name());
            oldVo.setLuckdawMoney(countUserMoney(outLayMap,category, Whether.NO.getDbIndex(),s));
            newVo.setLuckdawMoney(countUserMoney(outLayMap,category, Whether.YES.getDbIndex(),s));
            allVo.setLuckdawMoney(oldVo.getLuckdawMoney().add(newVo.getLuckdawMoney()));

            cencesMasters.add(newVo);
            cencesMasters.add(oldVo);
            baseMapper.insertAll(allVo);
            baseMapper.insertAll(newVo);
            baseMapper.insertAll(oldVo);
        });
        CencesOutlay item = new CencesOutlay(0, "all", time, 2, 1,MyConfig.getEnv());
        //新用户全部
        CencesOutlay newAll = new CencesOutlay(0, "all", time, 1, 1,MyConfig.getEnv());
        //老用户全部
        CencesOutlay oldAll = new CencesOutlay(0, "all", time, 0, 1,MyConfig.getEnv());

        cencesMasters.forEach(vo -> {
            sumBy(item, vo);
            if (vo.getCategory().equals(1)) {
                sumBy(newAll, vo);
            }
            if (vo.getCategory().equals(0)) {
                sumBy(oldAll, vo);
            }
        });
        baseMapper.insertAll(item);
        baseMapper.insertAll(newAll);
        baseMapper.insertAll(oldAll);
        //渠道的全部
        brand.forEach(s -> {
            CencesOutlay sjy = new CencesOutlay(0, s, time, 2, 1,MyConfig.getEnv());
            cencesMasters.forEach(vo -> {
                if (vo.getBrand().equals(s)) {
                    sumBy(sjy, vo);
                }
            });
            baseMapper.insertAll(sjy);
        });
        cencesMsgMongodb.save(new CencesMsg("返佣统计",(System.currentTimeMillis()-starTime)));
    }



    private void sumBySdkMoney(CencesOutlay newVo, SdkMoney vo) {
        if(vo.getType()>0){
            newVo.setVideoMoney(newVo.getVideoMoney().add(vo.getMoney().divide(W,2,BigDecimal.ROUND_DOWN)));
        }else {
            newVo.setVideoMoney(newVo.getVideoMoney().add(vo.getMoney().divide(B,2,BigDecimal.ROUND_DOWN)));
        }
    }

    private void recordClick(MemberClidkRouseRecord v, CencesOutlay newVo) {
        if (v.getRewardType() .equals(RewardTypeUscan.Point.getIndex())) {
            newVo.setEarnClcikMoney(newVo.getEarnClcikMoney().add(new BigDecimal(v.getWorth()).divide(W, 2, BigDecimal.ROUND_DOWN)));
        } else {
            newVo.setEarnClcikMoney(newVo.getEarnClcikMoney().add(new BigDecimal(v.getWorth()).divide(B, 2, BigDecimal.ROUND_DOWN)));
        }
    }

    private void record(DownloadMemberRecord v, CencesOutlay newVo) {
        if (v.getStatus() == DownStatus.SUCCESS.getIndex()) {
            if (v.getRewardType() .equals(RewardTypeUscan.Point.getIndex())) {
                newVo.setEarnMoney(newVo.getEarnMoney().add(new BigDecimal(v.getMoney()).divide(W, 2, BigDecimal.ROUND_DOWN)));
            } else {
                newVo.setEarnMoney(newVo.getEarnMoney().add(new BigDecimal(v.getMoney()).divide(B, 2, BigDecimal.ROUND_DOWN)));
            }
        }
    }

    public CencesOutlay sumData(Integer star, Integer end, String appStore, int category, int type, String likeBrand) {
        return baseMapper.sumData(star, end, appStore, category, type,likeBrand,MyConfig.getEnv());
    }

    private void sumBy(CencesOutlay item, CencesOutlay vo) {
        item.setNewhandMoney(item.getNewhandMoney().add(vo.getNewhandMoney()));
        item.setRecordMoney(item.getRecordMoney().add(vo.getRecordMoney()));
        item.setSdkMoney(item.getSdkMoney().add(vo.getSdkMoney()));
        item.setEarnMoney(item.getEarnMoney().add(vo.getEarnMoney()));
        item.setEarnClcikMoney(item.getEarnClcikMoney().add(vo.getEarnClcikMoney()));
        item.setMasterMoney(item.getMasterMoney().add(vo.getMasterMoney()));
        item.setLuckdawMoney(item.getLuckdawMoney().add(vo.getLuckdawMoney()));
        item.setVideoMoney(item.getVideoMoney().add(vo.getVideoMoney()));
        item.setXianwanMoney(item.getXianwanMoney().add(vo.getXianwanMoney()));
        item.setTaojinMoney(item.getTaojinMoney().add(vo.getTaojinMoney()));
        item.setJuxiangwanMoney(item.getJuxiangwanMoney().add(vo.getJuxiangwanMoney()));
        item.setDuoyouMoney(item.getDuoyouMoney().add(vo.getDuoyouMoney()));
        item.setAotianMoney(item.getAotianMoney().add(vo.getAotianMoney()));
        item.setPceggMoney(item.getPceggMoney().add(vo.getPceggMoney()));
        item.setYwhzMoney(item.getYwhzMoney().add(vo.getYwhzMoney()));
    }

    private static final BigDecimal B = new BigDecimal(100);
    private static final BigDecimal W = new BigDecimal(10000);

    private void sumByVo(CencesOutlay item, DownloadMemberRecord vo) {
        if (vo.getRewardType().equals(RewardTypeUscan.Point.getIndex())) {
            item.setRecordMoney(item.getRecordMoney().add(new BigDecimal(vo.getMoney()).divide(B, 2, BigDecimal.ROUND_DOWN)));
        } else {
            item.setRecordMoney(item.getRecordMoney().add(new BigDecimal(vo.getMoney()).divide(W, 2, BigDecimal.ROUND_DOWN)));
        }
    }

    public int deleteByTime(int time) {
        CencesOutlayExample earnDayExample = new CencesOutlayExample();
        earnDayExample.createCriteria().andTimeEqualTo(time).andAppIdEqualTo(MyConfig.getEnv());
        return baseMapper.deleteByExample(earnDayExample);
    }

    /**
     * 统计用户收入
     * @param outLayMap 用户收入
     * @param category 任务分类
     * @param isNewMember 新老用户
     * @param appStore 渠道
     * @return 返回内容
     */
    private BigDecimal countUserMoney(Map<String, List<OutLayCount>> outLayMap, StringBuffer category, Integer isNewMember, String appStore) {
        BigDecimal money = BigDecimal.ZERO;
        List<OutLayCount> outLayCounts = outLayMap.get(category+":"+appStore+":"+isNewMember);
        if(null==outLayCounts){
            return money;
        }
        for(OutLayCount outLayCount :outLayCounts){
            money=money.add(outLayCount.getCount());
        }
        return money;
    }

}
